<?php
namespace Qgs\Controller;

use Think\Controller;
use Think\Model;


class PurchaseController extends BaseController {

    /**
     * 采购商品列表
     */
    public function index() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'a.last_modify');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $this->assign('order', $order);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);
        $defaultnum = C('MIN_STORE') ? C('MIN_STORE'): 500;
        $this->assign('defaultnum', $defaultnum);

        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = I('param.search');
        $local_id = session('userInfo')['local_id'];
        if (!$local_id) {
            $this->error('登陆信息错误, 请重新登陆', U('Login/loginOut'));
        }
        $where[] = ' 1=1 ';
        $where[] = ['a.local_id'=>$local_id];
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search_field', $search_field);
            $this->assign('search', $search);
        }

        $count = M('b2c_store_p_goods')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_products b on a.product_id=b.product_id')
            ->where($where)
            ->count();
        $maxpage = ceil($count/$num);
        if ($p > $maxpage) {
            $p = $maxpage;
        }
        $this->assign('p', $p);
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();

        $fields = 'a.goods_id,a.product_id,a.price,a.store,b.barcode,b.bn,b.`name`,b.spec_info';
        $data = M('b2c_store_p_goods')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_products b on a.product_id=b.product_id')
            ->where($where)
            ->field($fields)
            ->page($p, $num)
            ->order($order)
            ->select();
        $this->assign('list', $data);
        $this->assign('page', $show);
        $this->display();
    }


    private function _index_sql($fields, $where='', $order='', $limit='') {
        /**
        select a.p_relation_id,a.goods_id,a.product_id,b.barcode,b.bn,b.`name`,b.spec_info,c.store,c.price
        from sdb_b2c_product_relation a
        INNER JOIN sdb_b2c_products b on a.product_id=b.product_id
        LEFT JOIN(
        select * from sdb_b2c_store_p_goods where local_id=1
        ) c on a.product_id = c.product_id
        where a.product_type_id=2
         */
        $local_id = session('userInfo')['local_id'];
        if (is_array($fields)) {
            $fields = join(',', $fields);
        }
        if (is_array($where)) {
            $where = ' and '.join(' and ', $where);
        }
        $o = '';
        if (is_array($order) && !empty($order)) {
            if ($order[0]) {
                foreach ($order as $item) {
                    $k = end(array_keys($item));
                    $v = $item[$k];
                    $o .= " {$k} {$v},";
                }
                $o = rtrim($o, ',');
            } else {
                $k = end(array_keys($order));
                $v = $order[$k];
                $o = " {$k} {$v} ";
            }
            $o = ' order by '.$o;
        }
        $sql = "select {$fields} from ".C('DB_PREFIX')."b2c_product_relation a ";
        $sql .= " INNER JOIN ".C('DB_PREFIX')."b2c_products b on a.product_id=b.product_id ";
        $sql .= " LEFT JOIN( select product_id,store,price from ".C('DB_PREFIX')."b2c_store_p_goods where local_id={$local_id} ) c on a.product_id = c.product_id ";
        $sql .= " where a.product_type_id=2 {$where} {$o} {$limit}";
        return $sql;
    }

    /**
     * 添加商品到我的采购蓝
     */
    public function addToCart() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $product_id = I('post.product_id');
        $num = I('post.num');
        if (!$product_id || !$num) {
            $return = array(
                'status' => false,
                'message' => '缺少参数',
            );
            $this->ajaxReturn($return);
        }
        $local_id = session('userInfo')['local_id'];
        //查询这个店铺和产品的价格
        /**
        select a.guidance_price,b.price,b.store from sdb_b2c_product_relation a LEFT JOIN (
        select product_id,store,price from sdb_b2c_store_p_goods where local_id=1
        ) b on a.product_id=b.product_id
        where a.product_type_id=2 and a.product_id=1689
         */
        $sql = "select a.guidance_price,a.goods_id,b.price,b.store from ".C('DB_PREFIX')."b2c_product_relation a LEFT JOIN ( ";
        $sql .= " select product_id,store,price from ".C('DB_PREFIX')."b2c_store_p_goods where local_id={$local_id} ";
        $sql .= " ) b on a.product_id=b.product_id where a.product_type_id=2 and a.product_id={$product_id} limit 1";
        $model = new Model();
        $res = $model->query($sql);
        //修正数据
        $price = $res[0]['price'] ? $res[0]['price']: $res[0]['guidance_price'];
        if ($res[0]['store'] > $num) {
            $store = $res[0]['store'];
        } else {
            $store = $num;
        }
        //查询购物篮 如果有这执行修改(增加)
        $where = array(
            'local_id' => $local_id,
            'product_id' => $product_id,
        );
        $min_sum = $res[0]['store'] ? $res[0]['store']: C('MIN_STORE');
        $info = M('b2c_purchase_producttemp')->where($where)->order('id desc')->find();
        if ($info) {
            //更新数据
            $where = array('id'=>$info['id']);
            $data = array(
                'purc_sum' => $info['purc_sum'] + $store,
                'purc_price' => $price,
                'min_sum' =>$min_sum,
            );
            $result = M('b2c_purchase_producttemp')->where($where)->save($data);
        } else {
            //插入购物篮
            $add = array(
                'local_id' => $local_id,
                'goods_id' => $res[0]['goods_id'],
                'product_id' => $product_id,
                'purc_price' => $price,
                'purc_sum' => $store,
                'min_sum' => $min_sum,
            );
            $result = M('b2c_purchase_producttemp')->add($add);
        }

        if ($result) {
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    public function shoppingCart() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('p', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $this->assign('order', $order);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);
        $defaultnum = C('MIN_STORE') ? C('MIN_STORE'): 500;
        $this->assign('defaultnum', $defaultnum);

        $order = array($order_field => $order);

        $search_field = I('param.search_field');
        $search = I('param.search');
        $where[] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search_field', $search_field);
            $this->assign('search', $search);
        }
        $local_id = session('userInfo')['local_id'];
        if (!$local_id) {
            $this->error('登陆信息错误, 请重新登陆', U('Login/loginOut'));
        }
        $where[] = array('local_id'=>$local_id);
        $where[] = array('b.product_type_id' => '2');
        $count = M('b2c_purchase_producttemp a')
            ->join(C('DB_PREFIX').'b2c_product_relation b on a.product_id=b.product_id')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id=c.product_id')
            ->where($where)
            ->count();
        //购物篮不做分页
        /*$Page = new \Think\Page($count, $num);
        $show = $Page->show();*/
        $list = array();
        if ($count > 0) {
            $fields = 'a.*,c.`name`,c.barcode,c.bn,c.spec_info';
            $list = M('b2c_purchase_producttemp a')
                ->join(C('DB_PREFIX').'b2c_product_relation b on a.product_id=b.product_id')
                ->join(C('DB_PREFIX').'b2c_products c on a.product_id=c.product_id')
                ->field($fields)
                ->where($where)
                ->order($order)
                ->select();
        }
        $this->assign('list', $list);
        $this->display();
    }

    public function cartdel() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $data = I('post.data');
        $ids = $data['id'];
        if (is_array($ids)) {
            $ids = join(',', $ids);
        }
        $res = M('b2c_purchase_producttemp')->delete($ids);
        if ($res !== false) {
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    public function cartSubmit() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $local_id = session('userInfo')['local_id'];
        $data = I('post.data');
        $mark = I('post.mark');

        $total_price = 0;
        $items = array();
        if (is_array($data) && !empty($data)) {
            foreach ($data as $item) {
                $res = $this->getLastProductInfo($local_id, $item['product_id'], $item['purc_sum']);
                if (!$res['status']) {
                    $this->ajaxReturn($res);
                } else {
                    $total_price += ($res['data']['purc_price'] * $item['purc_sum']);
                    //$item['price'] = $res['data']['purc_price'];
                    $items[] = $res['data'];
                }
            }
        } else {
            $return = array(
                'status' => false,
                'message' => '没有数据或者是数据的格式出错',
            );
            $this->ajaxReturn($return);
        }

        //订单表汇总记录处理
        $datas = array(
            'local_id' => $local_id,
            'purc_price' => $total_price,
            'status' => '0',
            'uptime' => time(),
            'last_modify' => time(),
            'remark' => $mark,
        );
        $db = new Model();
        $db->startTrans();
        $res = M('b2c_purchase')->add($datas);
        if (!$res) {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '失败1',
            );
            $this->ajaxReturn($return);
        }
        //往b2c_purchase_product中插入采购的货品详细信息
        $where = array();
        foreach ($items as $v) {
            $add = array_merge($v, array('purc_id'=>$res));
            $r = M('b2c_purchase_product')->add($add);

            if (!$r) {
                $db->rollback();
                $return = array(
                    'status' => false,
                    'message' => '失败2',
                );
                $this->ajaxReturn($return);
            }
            $where[] = array(
                'product_id'=>$v['product_id'],
                'local_id'=>$local_id,
            );
        }
        //删除采购蓝提交的货品
        if (empty($where)) {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '失败3',
            );
            $this->ajaxReturn($return);
        } else {
            $where['_logic'] = 'or';
            $d = M('b2c_purchase_producttemp')->where($where)->delete();
            //var_dump(M('b2c_purchase_producttemp')->getLastSql());die;
            if ($d !== false) {
                $db->commit();
                $return = array(
                    'status' => true,
                    'message' => '成功',
                );
            } else {
                $db->rollback();
                $return = array(
                    'status' => false,
                    'message' => '失败3',
                );
            }
            $this->ajaxReturn($return);
        }
    }

    public function getLastProductInfo($local_id, $product_id, $num) {
        $sql = "select a.guidance_price,a.goods_id,b.price,b.store from ".C('DB_PREFIX')."b2c_product_relation a LEFT JOIN ( ";
        $sql .= " select product_id,store,price from ".C('DB_PREFIX')."b2c_store_p_goods where local_id={$local_id} ";
        $sql .= " ) b on a.product_id=b.product_id where a.product_type_id=2 and a.product_id={$product_id} limit 1";
        $model = new Model();
        $res = $model->query($sql);
        //修正数据
        $price = $res[0]['price'] ? $res[0]['price']: $res[0]['guidance_price'];
        if ($res[0]['store'] > $num) {
            $return = array(
                'status' => false,
                'message' => '该商品的起够数量已更新,下单失败,请重新挑选',
            );
            return $return;
        }
        return $return = array(
            'status' => true,
            'message' => '',
            'data' => array(
                'goods_id' => $res[0]['goods_id'],
                'purc_price' => $price,
                'product_id' => $product_id,
                'purc_sum' => $num,
            )
        );
    }

    public function shoppingList() {
        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 20);
        $search_field = I('get.search_field');
        $search = I('get.search');

        $order_field = I('get.order_field', 'last_modify');
        $order = I('param.order', 'desc');

        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);
        $this->assign('p', $page);

        if ($order_field && $order) {
            $order = "{$order_field} {$order}";
            $this->assign('order_field', $order_field);
        } else {
            $order = " last_modify desc";
        }

        $status = I('get.view', '0');
        if ($status) {
            $view = $status;
        } else {
            $view = '0';
        }
        $this->assign('view', $view);
        $local_id = session('userInfo')['local_id'];
        $where[] = ' 1=1 ';
        $where[] = array('b.local_id'=>$local_id);
        if ($status !== '' && $status != 4) {
            $where[] = array('a.status'=>$status);
        }
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search', $search);
            $this->assign('search_field', $search_field);
        }
        $count = M('b2c_purchase a')
            ->join(C('DB_PREFIX').'webpos_local_store b on a.local_id=b.local_id')
            ->where($where)
            ->count();

        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = array(
            'a.*',
            'b.local_name',
            'b.principal',
            'b.tel',
            'b.mobile',
            'b.local_type',
            'b.local_number',
        );
        $list = M('b2c_purchase a')
            ->join(C('DB_PREFIX').'webpos_local_store b on a.local_id=b.local_id')
            ->where($where)
            ->field($fields)
            ->order($order)
            ->page($page, $num)
            ->select();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    public function get_purchase_logs() {
        $purc_id = I('get.purc_id');
        if (!$purc_id) {
            $return = array(
                'status' => true,
                'message' => '参数缺失',
            );
            $this->ajaxReturn($return);
        }
        $logs = M('b2c_purchase_logs')
            ->where(array('purc_id'=>$purc_id))
            ->select();
        $statuss = array('已提交', '处理中', '已完成', '已取消');
        if ($logs) {
            foreach ($logs as &$item) {
                $item['before_status'] = $statuss[$item['before']];
                $item['later_status'] = $statuss[$item['later']];
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            }
        }
        $this->ajaxReturn($logs);
    }

    public function change_status() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '错误的请求方式',
            );
        }
        $purc_id = I('post.purc_id');
        $before = I('post.before' ,'0');
        $status = I('post.status', false);
        $desc = I('post.desc');
        if (!$purc_id || $status === false) {
            $return = array(
                'status' => false,
                'message' => '参数缺失',
            );
        }

        if($return) {
            $this->ajaxReturn($return);
        }
        //todo 加入管理员信息 id和name
        //写入日志表
        $Qgs_info = session('userInfo');
        $log = array(
            'purc_id' => $purc_id,
            'manage_id' => $Qgs_info['id'], //默认给个1 以后在修改
            'manage_name' => $Qgs_info['username'], //以后修改
            'role' => '1', //0-平台 1-店铺
            'before' => $before,
            'later' => $status,
            'desc' => $desc,
            'create_time' => time(),
        );
        $db = new Model();
        $db->startTrans();
        $logs = M('b2c_purchase_logs')->add($log);
        $save = array(
            'status' => (string) $status,
            'last_modify'=>time(),
        );
        $res = M('b2c_purchase')->where(array('purc_id'=>$purc_id))->save($save);
        if ($logs !== false && $res !== false) {
            $db->commit();
        } else {
            $db->rollback();
        }
        if ($res) {
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => true,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    /**
     * 我的采购单的商品详情
     */
    public function products() {
        $purc_id = I('get.purc_id');
        if (!$purc_id) {
            $this->error('错误,缺少参数');
        }
        $this->assign('purc_id', $purc_id);
        //分页
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('p', $p);
        $this->assign('num', $num);

        //排序
        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $order = array($order_field => $order);

        //搜索
        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $where[] = array(
            'purc_id'=>$purc_id,
        );
        //求和
        $count = M('b2c_purchase_product a')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->where($where)
            ->count();

        //分页输出
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();

        $fields = array(
            'purc_price',
            'purc_sum',
            'name',
            'c.spec_info',
            'c.barcode',
            'c.bn',
            'a.product_id',
            'a.goods_id',
        );
        //列表
        $data = M('b2c_purchase_product a')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id')
            ->where($where)
            ->field($fields)
            ->page($p, $num)
            ->order($order)
            ->select();

        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }
}